<template>
	<view class="container">
		<!-- 导航栏 -->
		<view class="navTop">
			<u-navbar :is-back="false" title="胜经咨询" title-color="#333" bg-color="#fff"></u-navbar>
		</view>
		<!-- 主要内容区域 -->
		<view class="main-content">
			<!-- 登录说明提示 -->
			<view class="account-tip" v-if="!localIsLogin">
				本系统为企业内部使用，仅限授权用户登录访问。
			</view>
			<!-- 未登录状态提示 -->
			<view class="login-tip" v-if="!isLoggedIn">
				<u-empty text="请登录后查看企业信息" mode="permission" icon-size="120"></u-empty>
				<button class="login-btn" type="primary" @click="showLoginPopup">立即登录</button>
			</view>

			<!-- 已登录状态显示内容 -->
			<view v-else>
				<!-- 当前企业信息卡片 -->
				<view class="current-company-card" v-if="info.enterpriseName">
					<view class="card-header" v-if="info.enterpriseName!='暂无'">
						<text class="card-title">{{info.enterpriseName}}</text>
						<u-icon name="edit-pen" size="32" color="#2979ff" @click="toggleEditButtons"></u-icon>
						<!-- 编辑按钮区域 -->
						<view class="edit-buttons" v-if="showEditButtons">
							<u-button type="primary" size="mini" @click="navigateToEdit">编辑信息</u-button>
							<view class="button-divider"></view>
							<u-button type="error" size="mini" @click="exit">退出登录</u-button>
						</view>
					</view>



					<view class="company-info" v-if="userInfo.name!='暂无'">
						<image class="company-logo" :src="info.logo" mode="aspectFill"></image>

						<view class="info-details">
							<view class="info-row">
								<u-icon name="account" size="30" color="#666"></u-icon>
								<text class="info-text">{{userInfo.name||"暂无"}}</text>
							</view>
							<view class="info-row">
								<u-icon name="phone" size="30" color="#666"></u-icon>
								<text class="info-text">{{userInfo.phone||"暂无"}}</text>
							</view>
							<view class="info-row">
								<u-icon name="map" size="30" color="#666"></u-icon>
								<text class="info-text">{{info.address}}</text>
							</view>
						</view>
					</view>
					<view class="company-exit" v-else>
						<view class="info-tip">
							暂无公司信息，请联系管理员添加
						</view>
						<view class="exit">
							<u-button shape="circle" type="primary" @click="exit">退出登录</u-button>
						</view>
					</view>
				</view>

				<!-- 搜索区域 -->
				<view class="search-section" v-if="info.enterpriseName!='暂无'">
					<u-search placeholder="请输入关键词" height="80" v-model="keyword" shape="square"
						:action-style="actionStyle" bg-color="#fff" border-color="#eee" @search="search"
						@custom="search" @clear="handleClearSearch"></u-search>
				</view>

				<!-- 搜索结果列表 -->
				<view class="search-results" v-if="info.enterpriseName!='暂无'">
					<scroll-view scroll-y :style="{maxHeight:swiperHeight - 50 +'px'}" :scroll-into-view="intoView"
						enhanced="{{true}}" show-scrollbar="{{false}}" v-if="showList.length>0">
						<view class="result-card" v-for="(item,index) in showList" :key="index" :id="'search'+index"
							@click="lookInfo(item)">
							<image class="result-logo" :src="item.logo" mode="aspectFill"></image>
							<view class="result-info">
								<text class="company-name">{{item.enterpriseName}}</text>
								<view class="info-row">
									<text>主营业务:</text>
									<text class="info-text">{{item.mainBusiness}}</text>
								</view>
								<view class="info-row">
									<text>应用场景:</text>
									<text class="info-text">{{item.applicationScenario}}</text>
								</view>
							</view>
						</view>
					</scroll-view>
					<view class="empty-state" v-if="showList.length === 0">
						<u-empty :text="title" mode="search" icon-size="120"></u-empty>
					</view>
				</view>
			</view>
		</view>
		<!-- 分页组件 -->
		<view class="countPge" v-if="total > this.pageSize">
			<pagination ref="pagination" :total="total" page-type="2" :current="currentPage" :page-size="pageSize"
				background="transparent" @change="jumpPage">
			</pagination>
		</view>
		<!-- 登录弹窗 -->
		<u-popup v-model="showLoginModal" mode="bottom" height="400rpx" border-radius="20">
			<view class="getUserInfo">
				<button type="primary" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">手机号一键登录</button>
				<!-- <button v-if="localIsLogin" type="primary" @click="wxLogin">手机号一键登录</button> -->
				<view class="privacy-text">
					<u-icon :name="'/static/unselect.png'" size="40" v-if="!agreePolicy" @click="agreePolicy=true"></u-icon>
					<u-icon :name="'/static/select.png'" size="40" v-else @click="agreePolicy=false"></u-icon>
					<text class="title">登录即表示您已同意</text>
					<text class="privacy-link link" @click="openPrivacyContract">《用户隐私协议》</text>
					<text class="user-link link" @click="openAgreement">《用户协议》</text>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		appLogin,
		getCompanyInfo,
		getCustomerList
	} from "@/api/index.js"
	import {
		removeToken
	} from '@/utils/auth'
	import {
		toast,
		toastload,
		closeload,
		showConfirm,
		tiao
	} from "../../utils/common"
	import pagination from '@/components/pagination.vue'
	export default {
		components: {
			pagination
		},
		data() {
			return {
				agreePolicy:false,
				keyword: "",
				showList: [],
				actionStyle: {
					color: '#fff',
					fontSize: '14px',
					padding: '14rpx 0 ',
					borderRadius: '14rpx',
					backgroundColor: "#2979ff"
				},
				title: "请输入关键词进行查询",
				showLoginModal: false,
				pageSize: 10,
				total: 0,
				currentPage: 1,
				intoView: "",
				swiperHeight: "",
				isLoggedIn: false, // 登录状态
				phoneNumber: "",
				info: {
					enterpriseName: "暂无",
					address: "暂无",
					logo: ""
				},
				userInfo: {
					name: "暂无",
					phone: '暂无'
				},
				lastKeyword: "",
				needPrivacyAuthorization: false, // 是否需要隐私授权
				localIsLogin: false,
				showEditButtons: false // 新增：控制编辑按钮显示
			}
		},
		onLaunch() {
			// 全局分享配置（适用于所有页面）
			uni.onShareAppMessage(() => {
				return {
					title: '胜经企管咨询', // 默认标题
					path: '/pages/index/index', // 默认跳转路径
					imageUrl: '/static/logo.png', // 默认分享图片
				};
			});
		
			// 如果需要分享到朋友圈（微信小程序独有）
			uni.onShareTimeline(() => {
				return {
					title: '胜经企管咨询',
					query: '', // 自定义参数
					imageUrl: '/static/logo.png',
				};
			});
		},
		onLoad() {
			this.localIsLogin = uni.getStorageSync('access_token') ? true : false
		},

		async onShow() {
			this.phoneNumber = uni.getStorageSync("phone") || ""
			await this.checkLoginStatus();
			if (this.phoneNumber && this.isLoggedIn) {
				this.getInfo(this.phoneNumber)
			}
			// 检查隐私协议是否需要授权
			this.checkPrivacySetting();
		},
		methods: {
			// 切换编辑按钮显示状态
			toggleEditButtons() {
				this.showEditButtons = !this.showEditButtons;
			},

			// 检查隐私协议设置
			async checkPrivacySetting() {
				if (uni.getPrivacySetting) {
					try {
						const res = await this.getPrivacySetting();
						this.needPrivacyAuthorization = res.needAuthorization;
						console.log('隐私协议授权状态:', res);
					} catch (error) {
						console.error('获取隐私协议设置失败:', error);
					}
				}
			},

			// 获取隐私协议设置
			getPrivacySetting() {
				return new Promise((resolve, reject) => {
					uni.getPrivacySetting({
						success: res => resolve(res),
						fail: err => reject(err)
					});
				});
			},

			// 打开隐私协议
			openPrivacyContract() {
				uni.navigateTo({
					url: "/pages/privacyment/privacyment"
				})
			},

			openAgreement() {
				uni.navigateTo({
					url: "/pages/agreement/agreement"
				})
			},

			async initBoxSize() {
				const measure = (selector) => new Promise(resolve =>
					uni.createSelectorQuery()
					.select(selector)
					.boundingClientRect(data => resolve(data?.height || 0))
					.exec()
				);

				try {
					const [navH, boxH] = await Promise.all([
						measure('.navTop'),
						measure('.container')
					]);

					const [cardH = 0, searchH = 0] = this.isLoggedIn ? await Promise.all([
						measure('.current-company-card'),
						measure('.search-section')
					]) : [];

					const [footerH = 0] = this.total > this.pageSize ? [await measure('.countPge')] : [];

					this.swiperHeight = boxH - navH - cardH - searchH - footerH;
				} catch (error) {
					toast("高度异常:" + error)
					this.swiperHeight = 300;
				}
			},

			checkLoginStatus() {
				let token = uni.getStorageSync('access_token');
				this.isLoggedIn = !!token;
			},

			showLoginPopup() {
				this.showLoginModal = true;
			},

			getPhoneNumber(e) {
				console.log(e);
				if (e.detail.errno == "104") {
					toast("取消授权")
					this.showLoginModal = false;
					return
				}
				if (e.detail.errMsg === 'getPhoneNumber:fail user deny') {
					toast("用户拒绝授权")
					this.showLoginModal = false;
					return
				}
				if(!this.agreePolicy){
					toast("请先阅读并同意用户协议和隐私政策")
					return
				}

				toastload()
				appLogin({
					encryptedData: e.detail.encryptedData,
					iv: e.detail.iv,
					wxCode: e.detail.code
				}).then(res => {
					closeload()
					uni.setStorageSync('access_token', res.data.access_token);
					uni.setStorageSync('phone', res.data.phoneNumber)
					uni.setStorageSync("permission", res.data.permission || "user")
					this.phoneNumber = res.data.phoneNumber
					this.isLoggedIn = true;
					uni.setStorageSync("phone", this.phoneNumber)
					this.getInfo(this.phoneNumber)
					this.localIsLogin = true
				})
				this.showLoginModal = false;
			},

			wxLogin() {
				toastload()
				appLogin({
					phone: uni.getStorageSync('phone')
				}).then(res => {
					closeload()
					uni.setStorageSync('access_token', res.data.access_token);
					uni.setStorageSync('phone', res.data.phoneNumber)
					uni.setStorageSync("permission", res.data.permission || "user")
					this.phoneNumber = res.data.phoneNumber
					this.isLoggedIn = true;
					uni.setStorageSync("phone", this.phoneNumber)
					this.getInfo(this.phoneNumber)
				})
				this.showLoginModal = false;
			},

			async getInfo(phoneNumber) {
				try {
					toastload();
					const res = await getCompanyInfo({
						phoneNumber
					});

					if (res.code !== 200 || !res.data) {
						closeload();
						return;
					}
					this.info = res.data;
					this.userInfo = this.info.contacts.find(contact => contact.phone === phoneNumber);
					closeload();

				} catch (error) {
					closeload();
					toast("获取公司信息异常:" + error)
				}
			},

			//退出登录
			exit() {
				showConfirm("是否退出登录").then(res => {
					if (res.confirm) {
						removeToken()
						uni.removeStorageSync('permission')
						uni.redirectTo({
							url: '/pages/index/index'
						})
					}
				})
			},

			navigateToEdit() {
				if (this.info.enterpriseName == '暂无') {
					toast("暂无公司信息")
					return
				}
				uni.navigateTo({
					url: '/pages/edit/edit'
				});
				this.showEditButtons = false
			},

			lookInfo(item) {
				let id = item.id
				uni.navigateTo({
					url: `/pages/info/info?id=${id}`
				});
			},

			handleClearSearch() {
				this.keyword = "";
				this.currentPage = 1;
			},

			async search() {
				try {
					toastload("数据请求中...");
					if (this.keyword !== this.lastKeyword) {
						this.currentPage = 1;
						this.lastKeyword = this.keyword;
					}

					const params = {
						pageNum: this.currentPage,
						pageSize: this.pageSize,
						keyName: this.keyword
					};

					const res = await getCustomerList(params);

					if (!res.data) {
						throw new Error('暂无数据');
					}
					this.total = res.data.total;
					this.showList = res.data.list;
					this.$nextTick(this.initBoxSize);

				} catch (error) {
					toast('搜索数据异常:' + error)
				} finally {
					closeload();
				}
			},

			async jumpPage(e) {
				this.currentPage = e
				await this.search()

				// 回滚到顶部
				this.$nextTick(() => {
					this.intoView = 'search0'
				})
				this.intoView = ''
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f8f8f8;
	}

	.main-content {
		flex: 1;
		padding: 20rpx 24rpx;
		overflow: hidden;
	}

	/* 登录提示样式 */
	.login-tip {
		background: #fff;
		border-radius: 16rpx;
		padding: 60rpx 0;
		text-align: center;
		margin-bottom: 24rpx;

		.login-btn {
			margin: 40rpx auto 0;
			width: 60%;
		}
	}

	/* 当前企业卡片样式 */
	.current-company-card {
		position: relative;
		background: #fff;
		border-radius: 16rpx;
		padding: 24rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.03);
		max-height: 200px;

		.card-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 24rpx;
			position: relative;

			.card-title {
				font-size: 32rpx;
				font-weight: 600;
				color: #333;
			}
		}

		/* 新增：编辑按钮区域样式 */
		.edit-buttons {
			display: flex;
			flex-direction: column;
			position: absolute;
			right: 0;
			top: 50rpx;
			/* 调整位置在图标下方 */
			background-color: #fff;
			border-radius: 12rpx;
			box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.12);
			padding: 10rpx;
			z-index: 10;

			/* 小三角指示器 */
			&::before {
				content: "";
				position: absolute;
				top: -28rpx;
				right: 16rpx;
				border-width: 8px;
				border-style: solid;
				border-color: transparent transparent #fff transparent;
				filter: drop-shadow(0 -2rpx 2rpx rgba(0, 0, 0, 0.1)); 
			}

			button {
				flex: 1;
				margin: 0;
				border-radius: 0;
				height: 80rpx;
				font-size: 28rpx;

				/* 移除u-button默认的margin */
				&::after {
					display: none;
				}
			}

			.button-divider {
				height: 1rpx;
				background-color: #f0f0f0;
				margin: 5rpx 15rpx;
			}

			/* 第一个按钮圆角 */
			button:first-child {
				border-top-left-radius: 12rpx;
				border-top-right-radius: 12rpx;
			}

			/* 最后一个按钮圆角 */
			button:last-child {
				border-bottom-left-radius: 12rpx;
				border-bottom-right-radius: 12rpx;
			}
		}

		.company-exit {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;

			.info-tip {
				width: 100%;
				height: 100px;
				line-height: 100px;
				text-align: center;
				font-weight: 500;
			}
		}

		.company-info {
			display: flex;
			align-items: flex-start;

			.company-logo {
				width: 120rpx;
				height: 120rpx;
				border-radius: 8rpx;
				margin-right: 24rpx;
				background-color: #f5f5f5;
			}

			.info-details {
				flex: 1;

				.info-row {
					display: flex;
					align-items: center;
					margin-bottom: 16rpx;

					&:last-child {
						margin-bottom: 0;
					}

					.info-text {
						margin-left: 12rpx;
						font-size: 28rpx;
						color: #333;
					}
				}
			}
		}
	}

	/* 搜索区域 */
	.search-section {
		margin-bottom: 24rpx;
	}

	/* 搜索结果区域 */
	.search-results {
		background: #fff;
		border-radius: 16rpx;
		overflow: hidden;

		.results-scroll {
			max-height: calc(100vh - 300px);
		}

		.result-card {
			display: flex;
			padding: 24rpx;
			border-bottom: 1rpx solid #f0f0f0;

			&:last-child {
				border-bottom: none;
			}

			.result-logo {
				width: 130rpx;
				height: 130rpx;
				border-radius: 8rpx;
				margin-right: 20rpx;
				background-color: #f5f5f5;
			}

			.result-info {
				flex: 1;

				.company-name {
					display: block;
					font-size: 30rpx;
					font-weight: 500;
					color: #333;
					margin-bottom: 12rpx;
				}

				.info-row {
					display: flex;
					align-items: center;
					margin-bottom: 8rpx;

					&:last-child {
						margin-bottom: 0;
					}

					.info-text {
						margin-left: 8rpx;
						font-size: 26rpx;
						color: #333;
					}
				}
			}
		}

		.empty-state {
			padding: 60rpx 0;
		}
	}

	.countPge {
		width: 750rpx;
		background-color: #fff;
		padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
		position: fixed;
		bottom: 0rpx;
		left: 0;
		right: 0;
		z-index: 999;
	}

	/* 登录弹窗样式 */
	.getUserInfo {
		padding: 40rpx;

		button {
			margin-top: 40rpx;
		}

		.privacy-text {
			display: flex;
			align-items: center;
			margin-top: 20rpx;
			font-size: 26rpx;
			color: #666;
			text-align: center;
			.title{
				margin: 0 10rpx;
			}

			.link {
				color: #2979ff;
			}
		}
	}
	.account-tip {
		text-align: center;
		font-size: 24rpx;
		color: #999;
		margin: 20rpx 0;
	}

</style>